package by.pavlyukevich.paymentsystem.add;

import java.util.Iterator;

import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

import by.pavlyukevich.paymentsystem.dataaccess.filter.Filter;
import by.pavlyukevich.paymentsystem.datamodel.AbstractEntity;
import by.pavlyukevich.paymentsystem.services.AbstractService;

public abstract class AbstractDataProvider<Entity extends AbstractEntity<?>> extends
		SortableDataProvider<Entity, SingularAttribute<Entity, ?>> {

	private AbstractService<?, Entity> service;
	private Filter<Entity> filter;

	public AbstractDataProvider(SingularAttribute<Entity, ?> sortParam, Filter<Entity> filter,
			AbstractService<?, Entity> service) {
		super();
		this.filter = filter;
		this.service = service;
		setSort(sortParam, SortOrder.ASCENDING);
	}

	@Override
	public Iterator<? extends Entity> iterator(long startPosition, long maxResult) {
		SingularAttribute<Entity, ?> sortParam = getSort().getProperty();
		SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
		boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
		filter.setSortParam(sortParam).setMaxResult(maxResult).setStartPosition(startPosition)
				.setAscending(ascending);
		return service.getList(filter).iterator();
	}

	@Override
	public long size() {
		return service.getCount(filter);
	}

	@Override
	public IModel<Entity> model(Entity object) {
		return new CompoundPropertyModel<Entity>(object);
	}

}
